const BaseAdminController = require('./base_admin_controller.js');
const KnowledgeService = require('../../service/admin/knowledge_service.js');

class KnowledgeController extends BaseAdminController {

	/** 获取知识库列表 */
	async getList() {
		// 数据校验
		let rules = {
			search: 'string|min:1|max:30|name=搜索条件',
			sortType: 'string|name=搜索类型',
			sortVal: 'name=搜索类型值',
			orderBy: 'object|name=排序',
			whereEx: 'object|name=附加查询条件',
			page: 'must|int|default=1',
			size: 'int',
			isTotal: 'bool',
			oldTotal: 'int',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new KnowledgeService();
		let result = await service.getKnowledgeList(input);

		// 数据格式化
		let list = result.list;

		for (let k = 0; k < list.length; k++) {
			list[k].QUESTION = this.fmtHtml(list[k].QUESTION);
			list[k].ANSWER = this.fmtHtml(list[k].ANSWER);
		}

		return result;
	}

	/** 获取知识库详情 */
	async detail() {
		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new KnowledgeService();
		let knowledge = await service.getKnowledgeDetail(input.id);
		if (knowledge) {
			knowledge.QUESTION = this.fmtHtml(knowledge.QUESTION);
			knowledge.ANSWER = this.fmtHtml(knowledge.ANSWER);
		}
		return knowledge;
	}

	/** 添加知识库 */
	async insert() {
		// 数据校验
		let rules = {
			question: 'must|string|min:1|max:500|name=问题',
			answer: 'must|string|min:1|max:2000|name=答案',
			type: 'must|string|min:1|max:20|name=类型',
			status: 'int|default=1|in:0,1',
			order: 'int|default=9999',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new KnowledgeService();
		return await service.insertKnowledge(input);
	}

	/** 编辑知识库 */
	async edit() {
		// 数据校验
		let rules = {
			id: 'must|id',
			question: 'must|string|min:1|max:500|name=问题',
			answer: 'must|string|min:1|max:2000|name=答案',
			type: 'must|string|min:1|max:20|name=类型',
			status: 'int|default=1|in:0,1',
			order: 'int|default=9999',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new KnowledgeService();
		return await service.editKnowledge(input);
	}

	/** 删除知识库 */
	async delete() {
		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new KnowledgeService();
		return await service.deleteKnowledge(input.id);
	}

	/** 生成向量 */
	async generateVector() {
		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new KnowledgeService();
		return await service.generateVector(input.id);
	}
}

module.exports = KnowledgeController; 